package com.cactus.handler;

import cn.hutool.json.JSONUtil;
import com.cactus.entity.response.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: cactus
 * @CreateDate: 2023/9/14 12:49
 * @Description: authenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");
        if (e instanceof BadCredentialsException) {
            httpServletResponse.getWriter().write(JSONUtil.toJsonStr(new Result(401, null, e.getMessage())));
        } else if (e instanceof InsufficientAuthenticationException) {
            httpServletResponse.getWriter().write(JSONUtil.toJsonStr(new Result(402, null, "你的token已过期或者不存在!")));
        } else if (e instanceof UsernameNotFoundException) {
            httpServletResponse.getWriter().write(JSONUtil.toJsonStr(new Result(401, null, e.getMessage())));
        } else {
            httpServletResponse.getWriter().write(JSONUtil.toJsonStr(new Result(500, null, e.getMessage())));
        }

    }
}
